import md5 from 'js-md5'
import sha1 from 'js-sha1'
import qs from 'qs'
const Fly = require('flyio/dist/npm/wx')
const fly = new Fly()
import store from '@/stores/index'
import sensor from '@/plugins/sensor'
import resConfig from '@/utils/config'
import { log } from '@/utils/tools'
import { navigateTo } from '@/utils/navigateTo'
import $trackSDK from '@/plugins/BSNLAnalyticsSDK'
// #ifdef H5
import Bridge from '@/plugins/JSBridge'
// #endif

let timer = null
let loadingFlag = false
// const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
const msgWhiteList = [
  '/bihs/activity/full-give/message/list',
  '/invoice-app-api/invoice/detail',
  '/invoice-app-api/invoice/apply',
  '/my/info/logout/all/verify',
  '/goods/detail/box/list',
  '/my/info/logout/all',
  '/gift/paySuccess',
  '/api/gzh/jssdk/sign',
  '/stock/user/apply/parent',
  '/social-material/to-study',
  'https://oapi.dingtalk.com/robot/send?access_token=9f44ad3005cf5d10a6d19bb8e4c36da28103587030c40469d74b20a57a574211'
]
const errorControl = (message, url, request) => {
  setTimeout(function() {
    uni.stopPullDownRefresh()
  }, 500)
  console.log(request,111)
  if (request && request.headers.showMessage && msgWhiteList.indexOf(url) === -1 || !url) {
    uni.showToast({
      title: message || '服务器异常，请稍后再试',
      icon: 'none',
      duration: 3 * 1000
    })
    // #ifdef MP-WEIXIN
    if (message.length > 35) {
      uni.hideToast()
      uni.$emit('showToast', message)
    }
    // #endif
  } else {
    timer = setTimeout(() => {
      if (loadingFlag) {
        uni.hideLoading()
        loadingFlag = false
      }
    }, 500)
  }

  // if (!url.match('/robot/send') && request) {
  //   log({ err: { name: '接口请求Error', message }, url: url, info: request })
  // }
}
export function getSign(obj) {
  const arr = Object.keys(obj)
  arr.sort()
  let stringA = ''
  arr.forEach(function(item, index) {
    if (obj[item] === '' || obj[item] === null || obj[item] === undefined) {
      return
    }
    if (obj[item] instanceof Array && obj[item].length === 0) {
      return
    }
    if (obj[item] instanceof Object && Object.keys(obj[item]).length === 0) {
      return
    }
    stringA += item + '=' + obj[item] + '&'
  })
  const url = stringA + `key=91GAUJRfZzkXdWtq`
  // console.log('url', url)
  return md5(url).toLocaleUpperCase()
}
const baseURL = {
  TEST: ['http://172.16.6.121:10000/api', 'http://172.16.6.122:9000/api', 'https://bx-co-uat-appgateway.bsnlco.com/api'],
  UAT: ['https://bx-uat.bisinuolan.cn/api', 'https://bxuatapi.bisinuolan.cn/api', 'https://bx-co-uat-appgateway.bsnlco.com/api'],
  PROD: ['https://bx.bisinuolan.cn/api', 'https://bxapi.bisinuolan.cn/api', 'https://bx-co-sh-appgateway.bsnlco.com/api']
}

// 设置超时
fly.config.timeout = 300000
fly.config.baseURL = process.env.VUE_APP_API // api的baseURL
fly.config.headers = {
  showLoading: true,
  showMessage: true
}

// request拦截器
fly.interceptors.request.use((config) => {
  // 切换环境的功能
  const method = (config.method === 'POST') ? 'body' : 'params'
  // config.data = qs.stringify(config.data)
  if (config.headers && config.headers.showLoading && !(config[method] && config[method]['hideLoading'])) {
    clearInterval(timer)
    if (!loadingFlag) {
      loadingFlag = true
      uni.showLoading({
        title: '加载中'
      })
    }
  }

  const device_id = sensor.quick('getAnonymousID')
  if (store && store.state && store.state.token) {
    config.headers['Authorization'] = 'Bearer ' + store.state.token // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  config.headers = Object.assign({}, resConfig, config.headers, {
    timestamp: Math.floor(new Date().getTime() / 1000),
    device_id: device_id,
  })
  if (!config.isNot) {
    config[method] = Object.assign({}, resConfig, config[method], {
      timestamp: Math.floor(new Date().getTime() / 1000),
      device_ip: '',
      device_id: '',
      sensor_cookie_id: device_id
    })
    config[method].sign = getSign(config[method])
    if (config.method === 'POST' && config.headers['Content-Type'] !== 'application/json') {
      config.body = qs.stringify(config.body)
    }
  }
  // 佣金验签
  if (config.apiType === 'commission') {
    const envNode = uni.getStorageSync('envNode')
    const appConfig = uni.getStorageSync('__app_config_info__')
    // console.log(JSON.parse(JSON.parse(appConfig).common))
    let commission_h5 = ''
    if (appConfig) {
      const common = JSON.parse(appConfig || '{}').common
      if (common) {
        const urls = JSON.parse(common || '{}').urls
        if (urls) {
          commission_h5 = urls.commission_h5
        }
      }
    }
    if (commission_h5) {
      config.baseURL = commission_h5 + '/api'
      // console.log(config.baseURL)
    } else {
      if (process.env.VUE_APP_BUILD_TYPE !== 'PROD' && envNode) {
        config.baseURL = baseURL[envNode][2]
      } else {
        config.baseURL = process.env.VUE_APP_COMMISSION_API // api的baseURL
      }
    }
    const stamp = new Date().getTime()
    // 随机6位数
    const nonce = Math.floor(Math.random() * 999999)
    const bb = 'ojojioji:;;?@#-=UFJHFUfehu!SNJHUFp[][d' + stamp + nonce
    const sign = sha1(bb)
    config.headers['sign'] = sign
    config.headers['stamp'] = stamp
    config.headers['nonce'] = nonce
  }
  
  //自定义api前缀，取环境变量的数据，没有的话用custom_baseURL
  if(config.custom_baseURL){
    let process_url= process.env[config.custom_baseURL];
    config.baseURL = process_url? process_url: config.custom_baseURL;
  }
  return config
}, error => {
  // Do something with request error
  // console.log(error) // for debug
  Promise.reject(error)
})

// response 拦截器
fly.interceptors.response.use((response) => {
  const resData = response.data
  const request = response.request

  if (resData.code === 401) {
    store.dispatch('LOGOUT_USER')
    if (loadingFlag) {
      uni.hideLoading()
      loadingFlag = false
    }
    // #ifdef H5
    if (Bridge.isInApp) {
      try {
        /* eslint-disable */
        const pages =  getCurrentPages()
        /* eslint-disable-end */
        $trackSDK.track('bx.web.fadetoken.page', '', {
          page: pages[pages.length-1].__page__.fullPath,
          api: request.url,
          source: Bridge.isInAndroidApp ? 'Android' : 'iOS'
        })
      } catch(e) {
        console.log(e)
      }
      
    }
    // #endif
    if (request.url !== '/token/refresh') {
      navigateTo('/pages/login/index')
    }
  } else if (resData.code !== 0 && resData.code !== '000000' && resData.code !== 1002) {
    errorControl(resData.message || resData.msg, request ? request.url : '', request)
    return Promise.reject(resData);
  } else {
    timer = setTimeout(() => {
      if (loadingFlag) {
        uni.hideLoading()
        loadingFlag = false
      }
    }, 500)
  }

  return {
    success: resData.code === 0,
    ...resData
  }
}, error => {
  console.log("可能500等", error)
  let url = ''
  if (error.request && error.request.url) {
    url = error.request.url
  }
  errorControl(error.response && error.response.data ? error.response.data.message||error.response.data.msg : '服务器异常，请稍后再试', url, error.request)
  return Promise.reject({
    success: false,
    e: error
  })
})

export function requestNew(option) {
  const envNode = uni.getStorageSync('envNode')
  if (process.env.VUE_APP_BUILD_TYPE !== 'PROD' && envNode) {
    fly.config.baseURL = baseURL[envNode][1]
  } else {
    fly.config.baseURL = process.env.VUE_APP_MINI_API // api的baseURL
  }
  return fly.request(option.url, option.data || option.params, option)
}

export default function request(option) {
  const envNode = uni.getStorageSync('envNode')
  if (process.env.VUE_APP_BUILD_TYPE !== 'PROD' && envNode) {
    fly.config.baseURL = baseURL[envNode][0]
  } else {
    fly.config.baseURL = process.env.VUE_APP_API // api的baseURL
  }
  return fly.request(option.url, option.data || option.params, option)
}
